/*
 * Copyright (C) 2013 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.squareup.picasso;

import ohos.agp.components.Image;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.FrameAnimationElement;
import ohos.app.Context;
import ohos.media.image.PixelMap;

class ImageViewAction<errorResId> extends Action<Image> {

    Callback callback;
    Request data;

    ImageViewAction(Picasso picasso, Image imageView, Request data, int memoryPolicy, int networkPolicy, int errorResId,
                    Element errorDrawable, String key, Object tag, Callback callback, boolean noFade) {
        super(picasso, imageView, data, memoryPolicy, networkPolicy, errorResId, errorDrawable, key, tag, noFade);
        this.callback = callback;
        this.data = data;
    }

    @Override
    void complete(PixelMap result, Picasso.LoadedFrom from) {
        if (result == null) {
            throw new AssertionError(
                    String.format("Attempted to complete action with no result!\n%s", this));
        }

        Image target = this.target.get();
        if (target == null) {
            return;
        }
        Context context = picasso.context;
        boolean indicatorsEnabled = picasso.indicatorsEnabled;

        PicassoDrawable.setBitmap(target, context, result, from, noFade, indicatorsEnabled, data);

        if (callback != null) {
            callback.onSuccess();
        }
    }

    @Override
    void error(Exception e) {
         Image target = this.target.get();
        if (target == null) {
            return;
        }

        Element placeholder = target.getImageElement();
        if (placeholder instanceof FrameAnimationElement) {
            ((FrameAnimationElement) placeholder).stop();
        }
        if (errorResId != 0) {
            target.setPixelMap(errorResId);
        } else if (errorDrawable != null) {
            target.setImageElement(errorDrawable);
        }
        if (callback != null) {
            callback.onError(e);
        }
    }

    @Override
    void cancel() {
        super.cancel();
        if (callback != null) {
            callback = null;
        }
    }
}